﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using Coffee_Restaurant.DAL;
using Coffee_Restaurant.Database;
using MetroFramework;
using MetroFramework.Controls;

namespace Coffee_Restaurant.Forms.Items
{
    public partial class ItemManager : UserControl
    {
        private string _itemIdSelect;
        public int IdCategory { get; set; }
        public ItemManager()
        {
            InitializeComponent();

        }

        #region event datagridview

        private void dataGridViewItems_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)
        {
            Debug.WriteLine("validating cell");
            if (e.FormattedValue.ToString().Length > 0)
            {
                //validate price
                if (dataGridViewItems.Columns[e.ColumnIndex].Name.Contains("ItemPrice"))
                {
                    e.Cancel = !IsDecimals(e.RowIndex, e.FormattedValue.ToString()); // neu dung la false
                }
                else
                {
                    e.Cancel = !IsValidLength(e.RowIndex, e.FormattedValue.ToString()); // neu dung la false
                }
            }
            else
            {
                e.Cancel = false;
            }

        }

        private void dataGridViewItems_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //flag for editing
            if (dataGridViewItems.Rows[e.RowIndex].Cells["ItemId"].Value != null)
            {
                dataGridViewItems.Rows[e.RowIndex].Tag = "EditRow";

            }
            Debug.WriteLine("end edit cell");
            //neu nhu cell co gia tri lien quan toi tien te
            if (dataGridViewItems.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null && !string.IsNullOrEmpty(dataGridViewItems.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()))
            {
                //format display
                if (dataGridViewItems.Columns[e.ColumnIndex].Name.Contains("ItemPrice"))
                {
                    string inputData = dataGridViewItems.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    dataGridViewItems.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = String.Format("{0:0,0}", decimal.Parse(inputData));
                }
            }
        }

        private void dataGridViewItems_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            UpdateItem();
        }

        /// <summary>
        /// select ItemId for edit and delete
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridViewItems_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            //select header column thi index = -1 => exception
            if (e.RowIndex >= 0)
            {
                _itemIdSelect = dataGridViewItems.Rows[e.RowIndex].Cells["ItemId"].Value.ToString();
            }
        }


        //event procees key data delete
        private void dataGridViewItems_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete)
            {
                DeleteRowItem();
            }
        }

        #endregion
        #region validate function datagridview

        public bool IsDecimals(int rowIndex, string inputData)
        {
            const string pattern = @"\d+";
            const RegexOptions regexOptions = RegexOptions.Singleline;
            var regex = new Regex(pattern, regexOptions);
            if (regex.IsMatch(inputData))
            {
                dataGridViewItems.Rows[rowIndex].ErrorText = null;
                return true;
            }
            dataGridViewItems.Rows[rowIndex].ErrorText = "Dữ liệu nhập vào là dạng số.";
            return false;
        }

        public bool IsString(int rowIndex, string inputData)
        {
            const string pattern = @"^[a-zA-Z0-9\s]+$";
            const RegexOptions regexOptions = RegexOptions.Singleline;
            var regex = new Regex(pattern, regexOptions);
            if (regex.IsMatch(inputData))
            {
                dataGridViewItems.Rows[rowIndex].ErrorText = null;
                return true;
            }
            dataGridViewItems.Rows[rowIndex].ErrorText = "Dữ liệu nhập vào là ký tự và số.";
            return false;
        }


        public bool IsValidLength(int rowIndex, string inputData)
        {
            if (inputData.Length > 0)
            {
                dataGridViewItems.Rows[rowIndex].ErrorText = null;
                return true;
            }
            dataGridViewItems.Rows[rowIndex].ErrorText = "Dữ liệu nhập vào là ký tự và số.";
            return false;
        }
        #endregion
        #region function update delete add


        public void ReloadDataGridview()
        {
            RefreshDataGridview(null);
        }
        void frmAdd_BtnSave(string name)
        {
            RefreshDataGridview(null);
        }
        private void UpdateItem()
        {
            if (!string.IsNullOrEmpty(_itemIdSelect))
            {
                using (var db = new DatabaseEntities())
                {
                    //tim kiem theo ten ban
                    var idConvert = Int32.Parse(_itemIdSelect);
                    var model = db.Items.FirstOrDefault(t => t.ItemId == idConvert);
                    if (model != null)
                    {
                        var frmUpdate = new UpdateItem
                        {
                            ItemIdSelect = idConvert,
                            cbbCategory = { SelectedValue = model.ItemCategoriesId },
                            cbbDVT = { SelectedValue = model.Unit },
                            txtName = { Text = model.Name },
                            txtPrice = { Text = model.Price.ToString() },
                        };

                        frmUpdate.BtnSave += ReloadDataGridview;
                        frmUpdate.ShowDialog();
                    }
                }
            }
            else
            {
                CustomMessageBox.Show("Bạn chưa chọn mặt hàng cần xóa", "Thông báo", "alert", MetroColorStyle.Default);
            }
        }

        private void DeleteRowItem()
        {
            if (!string.IsNullOrEmpty(_itemIdSelect))
            {
                DialogResult dialogResult = CustomMessageBox.Show("Bạn thật sự muốn xóa mặt hàng này", "Xác nhận", "confirm", MetroColorStyle.Red);
                if (dialogResult == DialogResult.Yes)
                {
                    var itemDa = new ItemDa();
                    if (itemDa.Delete(Int32.Parse(_itemIdSelect)) > 0)
                    {
                        LoadCategoryItems();
                        RefreshDataGridview(null);
                    }
                }

            }
            else
            {
                CustomMessageBox.Show("Bạn chưa chọn mặt hàng cần xóa", "Thông báo", "alert", MetroColorStyle.Default);
            }
        }


        public void RefreshDataGridview(string keyword)
        {
            using (var db = new DatabaseEntities())
            {
                //clear trc khi load
                dataGridViewItems.Rows.Clear();
                //mac dinh la load tat ca
                var model = db.Items.ToList();
                if (!string.IsNullOrEmpty(keyword))
                {
                    model = db.Items.Where(x => x.Name.Contains(keyword)).ToList();
                }
                for (int i = 0; i < model.Count; i++)
                {
                    var item = model[i];
                    var row = new object[dataGridViewItems.ColumnCount];
                    row[0] = i + 1;
                    row[1] = item.ItemId;
                    row[2] = item.Name;
                    row[3] = item.Unit;
                    row[4] = item.Price;
                    row[5] = ItemCategoryDa.GetName(item.ItemCategoriesId);
                    row[6] = item.InWarehouse;
                    row[7] = item.Description;
                    dataGridViewItems.Rows.Insert(i, row);
                }
                dataGridViewItems.ClearSelection(); // disable auto selected row
            }
        }
        public void LoadCategoryItems()
        {
            using (var db = new DatabaseEntities())
            {
                var model = db.sp_ItemCategories().ToList();
                var sumCount = db.sp_ItemCategories().Sum(x => x.CountItems);
                treeViewItemCategory.Nodes.Clear();
                treeViewItemCategory.Nodes.Add("0", "Tất cả (" + sumCount + ")");
                foreach (var itemc in model)
                {
                    treeViewItemCategory.Nodes.Add(itemc.ItemCategoriesId.ToString(), itemc.Name + " (" + itemc.CountItems + ")");
                }
            }
        }
        private void UpdateCategoryItem()
        {
            if (IdCategory > 0)
            {
                using (var db = new DatabaseEntities())
                {
                    //tim kiem theo ten ban
                    var model = db.ItemCategories.FirstOrDefault(t => t.ItemCategoriesId == IdCategory);
                    if (model != null)
                    {
                        var frmUpdate = new UpdateCategory()
                        {
                            IdCategory = IdCategory,
                            txtName = { Text = model.Name },
                            txtDescription = { Text = model.Description },
                        };

                        frmUpdate.BtnSave += FrmUpdateOnBtnSave;
                        frmUpdate.ShowDialog();
                    }
                }
            }
            else
            {
                CustomMessageBox.Show("Bạn chưa chọn mặt hàng cần xóa", "Thông báo", "alert", MetroColorStyle.Default);
            }
        }

        private void FrmUpdateOnBtnSave(string id, string name)
        {
            LoadCategoryItems();
        }

        private void DeleteCategoryItem()
        {
            if (IdCategory > 0)
            {
                DialogResult dialogResult;
                int count = ItemCategoryDa.CountRef(IdCategory);
                if (count > 0)
                {
                    dialogResult = CustomMessageBox.Show("Nhóm này đang chứa (" + count + ") mặt hàng. Bạn thật sự muốn xóa tất cả", "Xác nhận", "confirm", MetroColorStyle.Red);
                }
                else
                {
                    dialogResult = CustomMessageBox.Show("Bạn thật sự muốn xóa nhóm hàng này", "Xác nhận", "confirm", MetroColorStyle.Red);

                }
                if (dialogResult == DialogResult.Yes)
                {
                    if (ItemCategoryDa.Delete(IdCategory) > 0)
                    {
                        //remove node tree
                        treeViewItemCategory.Nodes[IdCategory.ToString()].Remove();
                    }
                }

            }
            else
            {
                CustomMessageBox.Show("Bạn chưa chọn mặt hàng cần xóa", "Thông báo", "alert", MetroColorStyle.Default);
            }
        }
        #endregion
        #region xuatnhatkho event button

        private void btnImport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(_itemIdSelect))
            {
                using (var db = new DatabaseEntities())
                {
                    var idConvert = Int32.Parse(_itemIdSelect);
                    var model = db.Items.FirstOrDefault(t => t.ItemId == idConvert);
                    if (model != null)
                    {
                        var importWarehouse = new ImportItem()
                        {
                            lblItemName = { Text = model.Name },
                            lblDVT = { Text = model.Unit },
                            ItemIdSelect = model.ItemId,
                            txtPrice = { Text = model.Price.ToString() },
                        };
                        importWarehouse.BtnImport += ReloadDataGridview;
                        importWarehouse.ShowDialog();
                    }
                }
            }
            else
            {
                CustomMessageBox.Show("Bạn chưa chọn mặt hàng cần thao tác", "", "alert", MetroColorStyle.Default);

            }
        }


        private void btnExport_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(_itemIdSelect))
            {
                using (var db = new DatabaseEntities())
                {
                    var idConvert = Int32.Parse(_itemIdSelect);
                    var model = db.Items.FirstOrDefault(t => t.ItemId == idConvert);
                    if (model != null)
                    {
                        var exportItem = new ExportItem()
                        {
                            lblItemName = { Text = model.Name },
                            lblDVT = { Text = model.Unit },
                            ItemIdSelect = model.ItemId,
                            txtPrice = { Text = model.Price.ToString() },
                        };
                        exportItem.BtnExport += ReloadDataGridview;
                        exportItem.ShowDialog();
                    }
                }
            }
            else
            {
                CustomMessageBox.Show("Bạn chưa chọn mặt hàng cần thao tác", "", "alert", MetroColorStyle.Default);
            }

        }

        #endregion
        #region event toolstripmenu



        private void toolStripMenuItemAdd_Click(object sender, EventArgs e)
        {
            var frmAdd = new AddItem();
            frmAdd.BtnSave += frmAdd_BtnSave;
            frmAdd.ShowDialog();
        }


        private void sửaToolStripMenuItem_Click(object sender, EventArgs e)
        {
            UpdateItem();

        }

        private void toolStripMenuItemLoadItems_Click(object sender, EventArgs e)
        {
            RefreshDataGridview(null);
        }

        //menu strip delete row
        private void toolStripMenuItemDelete_Click(object sender, EventArgs e)
        {
            DeleteRowItem();
        }



        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            LoadCategoryItems();
        }

        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            var frmAdd = new AddCategory();
            frmAdd.BtnSave += FrmAddOnBtnSave;
            frmAdd.ShowDialog();
        }

        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            DeleteCategoryItem();
        }

        private void toolStripMenuItem3_Click(object sender, EventArgs e)
        {
            UpdateCategoryItem();
        }

        #endregion
        private void FrmAddOnBtnSave(string id, string name)
        {
            treeViewItemCategory.Nodes.Add(id, name);
        }

        private void treeViewItemCategory_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete)
            {
                DeleteCategoryItem();
            }
        }

        public void txtKeyword_TextChanged(object sender, EventArgs e)
        {
            var textbox = sender as MetroTextBox;
            if (textbox != null) RefreshDataGridview(textbox.Text);
        }
    }
}
